import React, {useEffect} from 'react';
import {GameState} from '../types';
import {Play, Pause, RotateCcw} from 'lucide-react';

interface SnakeGameProps {
    gameState: GameState;
    onDirectionChange: (direction: GameState['direction']) => void;
    onStart: () => void;
    onPause: () => void;
    onResume: () => void;
    gridSize: number;
}

export const SnakeGame: React.FC<SnakeGameProps> = ({
                                                        gameState,
                                                        onDirectionChange,
                                                        onStart,
                                                        onPause,
                                                        onResume,
                                                        gridSize
                                                    }) => {
    // AI 自动移动逻辑
    useEffect(() => {
        // 如果游戏未开始或已结束，则不执行 AI 逻辑
        if (!gameState.isPlaying || gameState.gameOver) return;

        // AI 决策函数：计算下一步移动方向
        const makeAIMove = () => {
            const head = gameState.snake[0];
            const food = gameState.food;

            // 计算蛇头与食物之间的坐标差值
            const dx = food.x - head.x;
            const dy = food.y - head.y;

            // 默认方向为当前方向
            let bestDirection = gameState.direction;

            // 根据坐标差值判断优先移动方向（水平优先）
            if (Math.abs(dx) > Math.abs(dy)) {
                bestDirection = dx > 0 ? 'RIGHT' : 'LEFT';
            } else {
                bestDirection = dy > 0 ? 'DOWN' : 'UP';
            }

            // 预测新蛇头位置（考虑边界环绕）
            const newHead = {...head};
            switch (bestDirection) {
                case 'UP':
                    newHead.y = (newHead.y - 1 + gridSize) % gridSize;
                    break;
                case 'DOWN':
                    newHead.y = (newHead.y + 1) % gridSize;
                    break;
                case 'LEFT':
                    newHead.x = (newHead.x - 1 + gridSize) % gridSize;
                    break;
                case 'RIGHT':
                    newHead.x = (newHead.x + 1) % gridSize;
                    break;
            }

            // 如果预测方向会导致撞到自己身体，则尝试其他方向
            if (gameState.snake.some(segment => segment.x === newHead.x && segment.y === newHead.y)) {
                const alternatives: GameState['direction'][] = ['UP', 'DOWN', 'LEFT', 'RIGHT'];
                for (const dir of alternatives) {
                    if (dir !== bestDirection) {
                        const testHead = {...head};
                        switch (dir) {
                            case 'UP':
                                testHead.y = (testHead.y - 1 + gridSize) % gridSize;
                                break;
                            case 'DOWN':
                                testHead.y = (testHead.y + 1) % gridSize;
                                break;
                            case 'LEFT':
                                testHead.x = (testHead.x - 1 + gridSize) % gridSize;
                                break;
                            case 'RIGHT':
                                testHead.x = (testHead.x + 1) % gridSize;
                                break;
                        }

                        // 如果该方向不会撞到自己，则选择该方向
                        if (!gameState.snake.some(segment => segment.x === testHead.x && segment.y === testHead.y)) {
                            bestDirection = dir;
                            break;
                        }
                    }
                }
            }

            // 执行方向更新
            onDirectionChange(bestDirection);
        };

        // 设置定时器，每隔一段时间执行 AI 移动（时间有轻微随机性，增加自然感）
        const aiMoveInterval = setInterval(makeAIMove, 300 + Math.random() * 200);
        return () => clearInterval(aiMoveInterval); // 组件卸载时清除定时器
    }, [gameState.snake, gameState.food, gameState.isPlaying, gameState.gameOver, gameState.direction, onDirectionChange, gridSize]);

    // 计算每个单元格的大小（像素）
    const cellSize = 400 / gridSize;

    return (
        <div className="bg-gray-900 p-6 rounded-xl shadow-2xl">
            {/* 顶部标题与分数 */}
            <div className="flex justify-between items-center mb-4">
                <h2 className="text-2xl font-bold text-white">AI Snake Game</h2>
                <div className="text-white">
                    <span className="text-lg font-semibold">Score: {gameState.score}</span>
                </div>
            </div>

            {/* 游戏画布区域 */}
            <div
                className="relative bg-black border-2 border-gray-700 rounded-lg mx-auto"
                style={{width: 400, height: 400}}
            >
                {/* 渲染蛇身体 */}
                {gameState.snake.map((segment, index) => (
                    <div
                        key={index}
                        className={`absolute rounded-sm ${
                            index === 0 ? 'bg-green-400 shadow-green-400/50 shadow-lg' : 'bg-green-500'
                        }`}
                        style={{
                            left: segment.x * cellSize,
                            top: segment.y * cellSize,
                            width: cellSize - 1,
                            height: cellSize - 1,
                        }}
                    />
                ))}

                {/* 渲染食物 */}
                <div
                    className="absolute bg-red-500 rounded-full shadow-red-500/50 shadow-lg animate-pulse"
                    style={{
                        left: gameState.food.x * cellSize + 2,
                        top: gameState.food.y * cellSize + 2,
                        width: cellSize - 4,
                        height: cellSize - 4,
                    }}
                />

                {/* 游戏结束遮罩层 */}
                {gameState.gameOver && (
                    <div className="absolute inset-0 bg-black/80 flex items-center justify-center rounded-lg">
                        <div className="text-center text-white">
                            <h3 className="text-2xl font-bold mb-2">Game Over!</h3>
                            <p className="text-lg mb-4">Final Score: {gameState.score}</p>
                        </div>
                    </div>
                )}
            </div>

            {/* 底部控制按钮区域 */}
            <div className="flex justify-center gap-4 mt-6">
                {/* 游戏未开始且未结束时显示“开始”按钮 */}
                {!gameState.isPlaying && !gameState.gameOver && (
                    <button
                        onClick={onStart}
                        className="flex items-center gap-2 px-6 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg font-semibold transition-colors"
                    >
                        <Play size={20}/>
                        Start AI Game
                    </button>
                )}

                {/* 游戏进行中显示“暂停”按钮 */}
                {gameState.isPlaying && (
                    <button
                        onClick={onPause}
                        className="flex items-center gap-2 px-6 py-3 bg-yellow-600 hover:bg-yellow-700 text-white rounded-lg font-semibold transition-colors"
                    >
                        <Pause size={20}/>
                        Pause
                    </button>
                )}

                {/* 游戏暂停但未结束时显示“继续”按钮 */}
                {!gameState.isPlaying && !gameState.gameOver && gameState.snake.length > 1 && (
                    <button
                        onClick={onResume}
                        className="flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-semibold transition-colors"
                    >
                        <Play size={20}/>
                        Resume
                    </button>
                )}

                {/* 游戏结束后显示“重新开始”按钮 */}
                {gameState.gameOver && (
                    <button
                        onClick={onStart}
                        className="flex items-center gap-2 px-6 py-3 bg-purple-600 hover:bg-purple-700 text-white rounded-lg font-semibold transition-colors"
                    >
                        <RotateCcw size={20}/>
                        New Game
                    </button>
                )}
            </div>
        </div>
    );
};
